/**
 * Copyright (c) 2009 Cerner Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Cerner Corporation - initial API and implementation
 */
package com.cerner.system.rest.jaas.cas;

import org.restlet.Client;
import org.restlet.data.Form;
import org.restlet.data.Response;
import org.restlet.data.Status;

/**
 * Internal HTTP-specific module that creates CAS ticket granting tickets (
 * {@code TGT}s) by {@code POST}ing to the {@code casLoginUrl}.
 * 
 * @author Alex Horn
 * @since 1.0.0
 */
class CasCredentialConnector {
  private final Client client;

  CasCredentialConnector(Client client) {
    this.client = client;
  }

  /**
   * Internal API to create a new CAS ticket granting ticket.
   * 
   * @return non-{@code null} CAS 1.0 {@code TGT}
   * @throws CasConnectorException if the credentials are invalid
   * @throws CasConnectorFault if an unrecoverable error occurred
   */
  String login(java.net.URI casLoginUrl, String username, char[] password)
      throws CasConnectorException, CasConnectorFault {
    final Form form = new Form();
    form.add("username", username);
    form.add("password", new String(password));

    final Response response;
    try {
      response = this.client.post(casLoginUrl.toString(),
          form.getWebRepresentation());
    } catch (Exception e) {
      throw new CasConnectorFault(e);
    }

    if (Status.SUCCESS_CREATED.equals(response.getStatus())) {
      return response.getLocationRef().getLastSegment();
    } else if (Status.CLIENT_ERROR_BAD_REQUEST.equals(response.getStatus())) {
      // http://jasig.princeton.edu/source/browse/jasigsvn/cas3/tags/cas-3-3-1-final/cas-server-integration-restlet/src/main/java/org/jasig/cas/integration/restlet/TicketResource.java?r=44327#l70
      throw new CasConnectorException(username, response.getStatus());
    } else {
      throw new CasConnectorFault(response.getStatus());
    }

  }
}
